layui.use(['form','table', 'ax','laydate','admin','layer',"yutons_sug"], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var laydate = layui.laydate;
    var admin = layui.admin;
    var form = layui.form;
    var layer = layui.layer;
    var yutons_sug = layui.yutons_sug;
    yutons_sug.render({
        id: "userNo", //设置容器唯一id
        height: "167",
        cols: [
            [{
                field:"userNo",
                title:"用户编号"
            },{
                field: 'userName',
                title: '员工姓名'
            }, {
                field: 'area',
                title: '所在区域'
            }]
        ], //设置表头
        params: [
            {
                name: 'userNo',
                field: 'userNo'
            }],//设置字段映射，适用于输入一个字段，回显多个字段
        type: 'sugTable', //设置输入框提示类型：sug-下拉框，sugTable-下拉表格
        url: Feng.ctxPath+"/wechatUser/list?userName=" //设置异步数据接口,url为必填项,params为字段名
    });
    lay('.datetime-input').each(function(){
        laydate.render({
            elem: this
            ,trigger: 'click'
            ,type: 'datetime'
        });
    });
    $.getJSON(Feng.ctxPath+"/orderForm/binsList",function(data){
        var binsList = data.data;
        $("#binsId").empty().append("<option value=''>全部称重设备</option>");
        for(var i=0;i<binsList.length;i++){
            var bins = binsList[i];
            $("#binsId").append("<option value='"+bins.id+"'>"+bins.binsNo+"</option>");
        }
        form.render("select");
    })

    /**
     * 字典类型表管理
     */
    var OrderForm = {
        tableId: "orderFormTable"
    };

    /**
     * 初始化表格的列
     */
    OrderForm.initColumn = function () {
        return [[

            {type: 'checkbox',fixed:"left"},
            {type:'numbers',title:"序号",fixed:"left"},
            {field: 'id', hide: true, title: '编号'},

            {field: 'id', sort: true, title: '订单编号',fixed:'left',templet:function(d){return d.id}}
            ,{field: 'userId', sort: true, title: '用户',templet:function(d){return d.userIdModel?d.userIdModel.userNo:"公益回收"}}
            ,{field:'userId',title:'姓名',templet:function(d){return _.defaultTo(d.userIdModel.userName,'公益回收');}}
            ,{field:'area',sort:true,title:'区域',templet:function(d){ return _.defaultTo(d.userIdModel.area,"未设置")}}
            ,{field: 'binsId', sort: true, title: '称重设备',templet:function(d){return d.binsIdModel.binsNo}}
            ,{field: 'wasteId', sort: true, title: '回收类别',templet:function(d){return d.wasteIdModel.typeName}}
            ,{field: 'state', sort: true, title: '状态',templet:function(d){return d.stateModel.name}}
            ,{field: 'wasteWeight', sort: true, title: '重量',templet:function(d){return (d.wasteWeight/1000).toFixed(2)+"千克"}}
            ,{field:"orderNo",title:'回收照片',templet:function(d){return (!d.orderNo || d.orderNo=='')?"暂无照片":"<a class='imgLink' onclick='return false' href='/upload/brand/"+d.orderNo+"' onmouseover='showImgTips(this)' target='_top'><img src='/upload/brand/"+d.orderNo+"'></a>"},event:"imgLinkClick"}
            //,{field: 'errorMsg', sort: true, title: '错误描述'}
            //,{field: 'errorCode', sort: true, title: '错误时间'}
            ,{field: 'price', sort: true, title: '积分'}
            ,{field: 'createTime', sort: true, title: '创建时间'}
            ,{field: 'finishTime', sort: true, title: '完成时间'}
            ,{field: 'errorMsg', sort: true, title: '回收执行日志'}
            ,{align: 'center', toolbar: '#tableBar', title: '操作',fixed:"right",minWidth:120}
        ]];
    };

    /**
     * 点击查询按钮
     */
    OrderForm.search = function () {
        var queryData = {};
        queryData['orderNo'] = $("#orderNo").val();
        queryData['userNo'] = $("#userNo").val();
        queryData['wasteId'] = $("#wasteId").val();
        queryData['wasteWeight'] = $("#wasteWeight").val();
        queryData['price'] = $("#price").val();
        queryData['totalPrice'] = $("#totalPrice").val();
        queryData['createTime'] = $("#createTime").val();
        queryData['state'] = $("#state").val();
        queryData['binsId'] = $("#binsId").val();
        queryData['finishTime'] = $("#finishTime").val();
        queryData['errorCode'] = $("#errorCode").val();
        queryData['errorMsg'] = $("#errorMsg").val();
        table.reload(OrderForm.tableId, {where: queryData,page: {
                curr: 1 //重新从第 1 页开始
            }});
    };

    /**
     * 弹出添加对话框
     */
    OrderForm.openAddDlg = function () {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '添加回收订单',
            content: Feng.ctxPath + '/orderForm/add',
            area:"650px",
            end: function () {
                admin.getTempData('formOk') && table.reload(OrderForm.tableId);
            }
        });
    };

    /**
     * 导出excel按钮
     */
    OrderForm.exportExcel = function () {
        var checkRows = table.checkStatus(OrderForm.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };
    OrderForm.delItems = function () {
        var checkRows = table.checkStatus(OrderForm.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要删除的数据");
        } else {
            var datas = checkRows.data;
            var params = [];
            for(var i=0;i<datas.length;i++){
                params.push(datas[i].id);
            }
            var paramsJson = JSON.stringify(params);
            $.ajax({
                type:"POST",
                url: Feng.ctxPath + "/orderForm/delItems",
                dataType:"json",
                contentType:"application/json", // 指定这个协议很重要
                data:paramsJson,
                async:false,
                //只有这一个参数，json格式，后台解析为实体，后台可以直接用
                success:function(data){
                    Feng.success("删除成功!");
                    table.reload(OrderForm.tableId);
                }
            })


        }
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    OrderForm.openEditDlg = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '修改回收订单',
            area:"650px",
            content: Feng.ctxPath + '/orderForm/edit?id=' + data.id,
            end: function () {
                admin.getTempData('formOk') && table.reload(OrderForm.tableId);
            }
        });
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    OrderForm.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/orderForm/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(OrderForm.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + OrderForm.tableId,
        url: Feng.ctxPath + '/orderForm/list',
        page: true,
        height: "full-98",
        cellMinWidth: 100,
        limit:30,
        cols: OrderForm.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        var validation = new Validation($("form")[0], {onSubmit:false});
        var validate = validation.validate();
        if(validate){
            OrderForm.search();
        }else{
            var serializeArray = $(".validation-failed");
            var errMsgs = "";
            for(var i=0;i<serializeArray.length;i++){
                var elemInfo = serializeArray[i];
                var elem = $("#"+elemInfo.name)[0];
                if(elem && elem.tooltip){
                    errMsgs+="<div><span style='color:dodgerblue'>"+elem.placeholder+"输入框有误：</span><span style='color:red'>"+elem.tooltip.content+"</span></div>"
                    var tipElem = elem.tagName=="SELECT"?$(elem).next():elem;
                    layer.tips(elem.tooltip.content,tipElem,{
                        tips: [1, '#FF99CC'],
                        time: 4000,
                        tipsMore: true
                    });
                }
            }
            //Feng.error(errMsgs);
        }
        return false;
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        OrderForm.openAddDlg();
        return false;
    });
    // 导出excel
    $('#btnExp').click(function () {
        OrderForm.exportExcel();
        return false;
    });
    $('#btnDel').click(function () {
        OrderForm.delItems();
        return false;
    });

    OrderForm.onShow = function(data){
        top.layui.admin.open({
            type: 2,
            title: '查看回收订单',
            content: Feng.ctxPath + '/orderForm/show?id=' + data.id,
        });
    }

    // 工具条点击事件
    table.on('tool(' + OrderForm.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            OrderForm.openEditDlg(data);
        } else if (layEvent === 'delete') {
            OrderForm.onDeleteItem(data);
        }else if(layEvent==='show'){
            OrderForm.onShow(data);
        }else if(layEvent==='imgLinkClick'){
            console.log(data);
            layer.open({
                area : "550px",
                content:"<img style='width:500px' src='/upload/brand/"+data.orderNo+"'/>"
            })
        }
        console.log(layEvent+":"+data)
    });

});
function showImgTips(aLink){
    console.log(aLink.href);
    layer.open({
        area : "550px",
        content:"<img style='width:500px' src='"+aLink+"'/>"
    })
}
